<?php

namespace App\Services\Warehouse\Services;

use App\Services\Warehouse\Interfaces\PartsServiceInterface;
use App\Services\Warehouse\Model\Parts;
use App\Services\Warehouse\Model\PartsInventory;
use App\Services\Warehouse\Model\PartsOperation;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\ApiV2Exception;
use Illuminate\Support\Facades\DB;

class PartsService implements PartsServiceInterface
{
    public function index($request)
    {
        $partsCode = $request['partsCode'] ?? '';
        $partsName = $request['partsName'] ?? '';
        $source = $request['source'] ?? '';
        $vendorId = $request['vendorId'] ?? '';
        $categoryId = $request['categoryId'] ?? '';
        $state = $request['state'] ?? '';
        $size = $request['size'] ?? 50;
        $data = DB::table('k_parts AS parts')
            ->leftJoin('k_vendor AS vendor', 'parts.vendorId', '=', 'vendor.id')
            ->leftJoin('k_parts_category AS parts_category', 'parts.categoryId', '=', 'parts_category.id')
            ->leftJoin('k_source AS source', 'parts.source', '=', 'source.id')
            ->leftJoin('k_parts_inventory AS inventory', 'inventory.parts_id', '=', 'parts.id')
            ->when($partsCode, function ($query) use ($partsCode) {
                return $query->where('parts.partsCode', $partsCode);
            })
            ->when($partsName, function ($query) use ($partsName) {
                return $query->where('parts.partsName', 'like', '%' . $partsName . '%');
            })
            ->when($source, function ($query) use ($source) {
                return $query->where('parts.source', $source);
            })
            ->when($vendorId, function ($query) use ($vendorId) {
                return $query->where('parts.vendorId', $vendorId);
            })
            ->when($categoryId, function ($query) use ($categoryId) {
                return $query->where('parts.categoryId', $categoryId);
            })
            ->when($state != null, function ($query) use ($state) {
                return $query->where('parts.state', $state);
            })
            ->select([
                'parts.*',
                'vendor.vendorName AS vendorName',
                'parts_category.categoryName AS categoryName',
                'source.name AS sourceName',
                'inventory.state AS state',
            ])
            ->orderBy("parts.updated_at", "desc")
            ->orderBy("parts.isScrap", "asc")
            ->paginate($size);
            
        foreach($data as $item){
            // return PartsInventory::STATES[$item->state];
            if(isset($item->state)){
                $item->state_name = PartsInventory::STATES[$item->state];
            }
            
        }
        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        
        $partsCode = $request['partsCode'];
        
        DB::beginTransaction(); 
        try {
            if ($id) {
                $data = Parts::query()->where('partsCode',$partsCode)->where('id','!=',$id)->first();
                if(!empty($data)){
                    throw new ApiV2Exception("配件编码不能重复");
                }
                $data = Parts::findOrFail($id);
            } else {
                $data = Parts::query()->where('partsCode',$partsCode)->first();
                if(!empty($data)){
                    throw new ApiV2Exception("配件编码不能重复");
                }
                $data = new Parts();
            }
            $uid = Auth::id();
            $request['user_id'] = $uid;
            $data->fill($request)->save();

            if(!$id){
                $PartsInventory = new PartsInventory();
                $InventoryData = array('parts_id'=>$data['id'],'fs_id'=>0,'state'=>PartsInventory::STATE_SET_UP,'po_id'=>0,'user_id'=>$uid);
                $PartsInventory->fill($InventoryData)->save();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            throw $e;
        }
        return $data->toArray();
    }

    public function get($id)
    {
        return Parts::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function information($partsCode){
        $data = DB::table('k_parts AS parts')
            ->leftJoin('k_vendor AS vendor', 'parts.vendorId', '=', 'vendor.id')
            ->leftJoin('k_parts_category AS parts_category', 'parts.categoryId', '=', 'parts_category.id')
            ->leftJoin('k_source AS source', 'parts.source', '=', 'source.id')
            ->leftJoin('k_parts_inventory AS inventory', 'inventory.parts_id', '=', 'parts.id')
            ->leftJoin('k_freight_space AS fs', 'inventory.fs_id', '=', 'fs.id')
            ->leftJoin('k_parts_operation AS operation', 'inventory.po_id', '=', 'operation.id')
            ->leftJoin('k_equipment AS equipment', 'operation.equipment_id', '=', 'equipment.id')
            ->where('parts.partsCode','=',$partsCode)
            ->select([
                'parts.*',
                'vendor.vendorName AS vendorName',
                'parts_category.categoryName AS categoryName',
                'source.name AS sourceName',
                'inventory.state AS state',
                'fs.position AS position',
                'equipment.equipmentCode AS equipmentCode',
            ])
            ->first();
        return $data;  
    }

    public function destroy($id)
    {
        $data = Parts::findOrFail($id);
        $data->delete();
    }

}
